/**
 * 校验用户名
 */
export function formCheckUser () {
  const validateUser = (_: any, value: string, callback: (data?: any) => void) => {
    if (/^[0-9A-Za-z]{4,20}$/.test(value)) {
      callback()
    } else {
      callback(new Error('账号必须是4-20位(数字、字符)'))
    }
  }
  return [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur'
    },
    {
      validator: validateUser,
      trigger: 'blur'
    }
  ]
}

/**
 * 校验密码
 * @param allowNull 是否允许位空
 * @returns {*[]}
 */
export function formCheckPass (allowNull = false) {
  const validatePass = (_: any, value: string, callback: (data?: any) => void) => {
    if (allowNull && (value === null || value === '')) {
      callback()
    } else if (/^[0-9A-Za-z]{6,20}$/.test(value)) {
      callback()
    } else {
      callback(new Error('账号必须是6-20位(数字、字符)'))
    }
  }
  const checkArr: Array<any> = [
    {
      validator: validatePass,
      trigger: 'blur'
    }
  ]
  if (!allowNull) {
    checkArr.unshift({
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    })
  }
  return checkArr
}

/**
 * 校验验证码
 */
export function formCheckCode () {
  const validateCode = (_: any, value: string, callback: (data?: any) => void) => {
    if (/^[0-9A-Za-z]{4}$/.test(value)) {
      callback()
    } else {
      callback(new Error('验证码必须是4位(数字、字符)'))
    }
  }
  return [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      validator: validateCode,
      trigger: 'blur'
    }
  ]
}

/**
 * 校验必须传值
 */
export function formCheckRequired (msg: string) {
  return [
    {
      required: true,
      message: msg,
      trigger: 'blur'
    }
  ]
}

/**
 * 时间校验
 * @param min 最小时间
 * @param max 最大时间
 */
export function formCheckDate (min: Date = new Date('2000/01/01'), max: Date = new Date('2100/01/01')) {
  const validateCode = (_: any, value: Date, callback: (data?: any) => void) => {
    if (!value) {
      callback(new Error('请选择时间'))
    } else if (min && min instanceof Date && min.getTime() > value.getTime()) {
      callback(new Error('不能小于最小时间'))
    } else if (max && min instanceof Date && max.getTime() < value.getTime()) {
      callback(new Error('不能大于最大时间'))
    } else {
      callback()
    }
  }
  return [
    {
      validator: validateCode,
      trigger: 'blur'
    }
  ]
}
